<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class User extends AdminBackEndController{
    public function __construct(){
        parent::__construct();
        $this->load->library('mypaging');
        $this->load->model('repo/user_model', 'user_model');
    }

    private function intialPaging($count_func, $paging_url_func, $options=array()){
        $this->mypaging->setCount($this->user_model->$count_func($options));
        $this->mypaging->setLimit(USER_LIMIT);
        $this->mypaging->setMainURL($paging_url_func());
        $this->mypaging->setSuffix($this->config->item('url_suffix'));
    }

    public function index($pageIndex=1){
        $aUser = array();
        $this->intialPaging('countUser', 'admin_user_paging_url', array('is_mod'=>$this->role==ROLE_MOD));
        $pagingBar = $this->mypaging->getBar($pageIndex);
        $offset    = ($pageIndex-1) * USER_LIMIT;
        if($this->role == ROLE_MOD){
            $aUser = $this->user_model->getAllUser(array(), array(), true, USER_LIMIT, $offset);
        } else {
            $aUser = $this->user_model->getAllUser(array(), array('a.deleted_at' => null), false, USER_LIMIT, $offset);
        }
        $aReturn = array(
            'pageTitle' => 'Danh sách người dùng',
            'pagingBar' => $pagingBar,
            'aUser'     => $aUser
            );
        $this->renderView('backend/admin/user/index', $aReturn);
    }

    public function search($pageIndex=1){
        $aUser = array();
        $search_key = $this->input->get('s', true);
        $this->intialPaging('countUser', 'admin_user_search_paging_url', array('search_key'=>$search_key, 'is_mod'=>$this->role==ROLE_MOD));
        $pagingBar = $this->mypaging->getBar($pageIndex, array('s' => $search_key));
        $offset    = ($pageIndex-1) * USER_LIMIT;
        if($this->role == ROLE_MOD){
            $aUser = $this->user_model->search($search_key, array(), array(), true, USER_LIMIT, $offset);
        } else {
            $aUser = $this->user_model->search($search_key, array(), array('a.deleted_at' => null), false, USER_LIMIT, $offset);
        }
        $aReturn = array(
            'pageTitle' => 'Danh sách người dùng',
            'pagingBar' => $pagingBar,
            'searchkey' => $search_key,
            'aUser'     => $aUser
            );
        $this->renderView('backend/admin/user/index', $aReturn);
    }

    public function newIndex(){
        $aReturn = array(
            'pageTitle' => 'Tạo người dùng'
            );
        $this->renderView('backend/admin/user/new', $aReturn);
    }

    public function newSubmit(){
        $aResult = array();
        $user  = $this->input->post('u', true);
        $tUser = $this->input->post('u');

        //validate data
        $this->form_validation->set_rules('u[username]', 'lang:username',   'trim|required|max_length[150]|min_length[5]|xss_clean');
        $this->form_validation->set_rules('u[email]',    'lang:info_email', 'trim|required|valid_email|max_length[150]');
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('insert_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>');
            $this->renderJSON($aResult);
            return;
        }

        //check for role
        $role = -1;
        if(!isset($tUser['role'])){
            $aResult = array('code'=>0, 'title' => $this->lang->line('system_error'));
        } else {
            $role = $this->encrypt->decode($tUser['role']);
            if($role==false){
                $aResult = array('code'=>0, 'title' => $this->lang->line('system_error'));
            } else {
                $aRole = array(ROLE_ADVERTISER);
                if($this->role==ROLE_ADMIN){
                    $aRole[] = ROLE_MOD;
                }
                if(in_array($role, $aRole)){
                    $user['role'] = $role;
                } else {
                    $aResult = array('code'=>0, 'title' => $this->lang->line('system_error'));
                }
            }
        }
        if(count($aResult)>0){
            $this->renderJSON($aResult);
            return;
        }

        $this->load->helper('string');
        $user['password'] = strtolower(random_string('alpha', 8));
        if(!isset($user['active_flg'])){
            $user['active_flg'] = 0;
        } else {
            $user['active_flg']=1;
        }
        $user['created_at'] = get_current_date();
        $user['image_folder'] = random_string('alnum', 18);

        $result = $this->user_model->insert($user);
        if($result){
            $aFolders = unserialize(PERSONAL_FOLDER);
            if($user['role']==ROLE_MOD){
                $aFolders[] = 'post';
            }
            makeShopImageFolderDir($user['image_folder'], $aFolders);
            $aResult = array(
                'code' => 1,
                'text' => $this->lang->line('insert_success'),
                'href' => admin_page_url(USER_SLUG)
                );
        } else {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('system_error'),
                'text' => '<ul><li>' . $this->lang->line('user_info_exist') . '</li></ul>'
                );
        }
        $this->renderJSON($aResult);
    }

    public function updateIndex(){
        $user_id = $this->input->get('u');
        if($user_id!=false){
            $user_id = $this->encrypt->decode($user_id);
            if($user_id==false){
                show_404();
            }
        } else {
            show_404();
        }
        $user = $this->user_model->getUserById($user_id);
        $this->renderView('backend/admin/user/update', array('pageTitle' => 'Cập nhật', 'user'=>$user));
    }

    public function updateSubmit(){
        $uId = 0;
        $aResult = null;
        $date = get_current_date();
        $user = $this->input->post('u', true);
        $tUser = $this->input->post('u');

        //validate data
        $this->form_validation->set_rules('u[full_name]', 'lang:info_user',    'trim|required|max_length[50]|min_length[5]|xss_clean');
        $this->form_validation->set_rules('u[phone]',     'lang:info_phone',   'trim|required|numeric|max_length[15]|min_length[10]|xss_clean');
        $this->form_validation->set_rules('u[address]',   'lang:info_address', 'trim|required|max_length[160]|min_length[10]|xss_clean');
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        if ($this->form_validation->run() == false) {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('update_fail'),
                'text' => '<ul>' . validation_errors() . '</ul>');
            $this->renderJSON($aResult);
            return;
        }

        //validate data
        if(!isset($tUser['id'])){
            $aResult = array('code'=>0, 'title' => $this->lang->line('system_error'));
        } else {
            $user['id'] = $this->encrypt->decode($tUser['id']);
            if($user['id']==false){
                $aResult = array('code'=>0, 'title' => $this->lang->line('system_error'));
            } else {
                $uId = $user['id'];
                unset($user['id']);
                unset($user['role']);
            }
        }
        if($aResult!=null){
            $this->renderJSON($aResult);
            return;
        }
        //set active flag
        if(isset($user['active_flg']) && $user['active_flg']==1){
            $user['active_flg']=1;
        } else {
            $user['active_flg']=0;
        }
        //set update time
        $user['updated_at'] = $date;
        //do update
        $result = $this->user_model->update($uId, $user);
        if($result){
            $aResult = array('code'=>1, 'text' => $this->lang->line('update_success'));
        } else {
            $aResult = array('code'=>0, 'title' => $this->lang->line('update_fail'));
        }
        $this->renderJSON($aResult);
    }

    public function resetUserPassword(){
        $user    = null;
        $aResult = array();
        $user_id = $this->input->post('id');
        if($user_id==false){
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('system_error')
                );
        } else {
            $user_id = $this->encrypt->decode($user_id);
            if($user_id==false){
                $aResult = array(
                    'code' => 0,
                    'title' => $this->lang->line('system_error')
                    );
            } else {
                $user = $this->user_model->getUserById($user_id);
            }
        }

        if(count($aResult)>0 || count($user)==0){
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('system_error')
                );
            $this->renderJSON($aResult);
            return;
        }

        $this->load->helper('string');
        $user->setPassword(strtolower(random_string('alpha', 8)));
        $data = array(
            'id'=>$user_id,
            'username'  => $user->getUsername(),
            'password'  => $user->getPassword(),
            'email'     => $user->getEmail(),
            'full_name' => $user->getFullName()
            );
        $result = $this->user_model->adminResetPassword($data);
        if($result){
            $aResult = array(
                'code' => 1,
                'text' => $this->lang->line('update_success')
                );
        } else {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('system_error')
                );
        }
        $this->renderJSON($aResult);
    }

    public function updateStateSubmit(){
        $aResult = array();
        $user_id = null;
        $oUser   = null;
        $user    = $this->input->post('user');
        if(!isset($user['id'])){
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('system_error')
                );
        } else {
            $user_id = $this->encrypt->decode($user['id']);
            if($user_id==false){
                $aResult = array(
                    'code' => 0,
                    'title' => $this->lang->line('system_error')
                    );
            } else {
                $oUser = $this->user_model->getUserById($user_id);

                if(!isset($user['active_flg']) || $user['active_flg']==0){
                    $oUser->setActiveFlg(0);
                } else {
                    $oUser->setActiveFlg(1);
                }
            }
        }

        if(count($aResult)>0 || count($oUser)==0){
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('system_error')
                );
            $this->renderJSON($aResult);
            return;
        }

        $result = $this->user_model->update($user_id, array('active_flg' => $oUser->getActiveFlg()));
        if($result){
            $aResult = array(
                'code' => 1,
                'text' => $this->lang->line('update_success')
                );
        } else {
            $aResult = array(
                'code' => 0,
                'title' => $this->lang->line('system_error')
                );
        }
        $this->renderJSON($aResult);
    }
}